package me.thinkjet.staticmng.service;

import com.jfinal.kit.PathKit;
import org.apache.commons.lang3.RandomStringUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Calendar;
import java.util.Date;

/**
 * 简单的文件上传实现
 * 可上传到又拍云或者本地
 * 图片上传请使用ImgService实现
 */
public class UploadService {

	private static final String SERVICE_DOMAIN = "http://static.siyanjing.net/";

	public static String uplaodFile(HttpServletRequest request) {
		return uploadToLocal(request, "/upload/files/");
	}

	public static String uplaodImg(HttpServletRequest request) {
		return uploadToLocal(request, "/upload/imgs/");
	}

	private static String uploadToLocal(HttpServletRequest request, String basePath) {
		String fileName = request.getParameter("fileName");
		String filePath = getFilePath(basePath);
		String newFileName = getFileName(fileName);
		String savePath = PathKit.getWebRootPath() + filePath;


		File file = new File(savePath);

		if (!file.exists()) {
			file.mkdirs();
		}
		try {
			InputStream input = request.getInputStream();
			FileOutputStream fos = new FileOutputStream(savePath + "/" + newFileName);
			int size = 0;
			byte[] buffer = new byte[1024];
			while ((size = input.read(buffer, 0, 1024)) != -1) {
				fos.write(buffer, 0, size);
			}
			fos.close();
			input.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return SERVICE_DOMAIN + filePath + "/" + newFileName;
	}

	private static String getFilePath(String basePath) {
		Calendar calender = Calendar.getInstance();
		return basePath + calender.get(Calendar.YEAR) + "/"
				+ (calender.get(Calendar.MONTH) + 1);
	}

	private static String getFileName(String fileName) {
		return new Date().getTime()
				+ RandomStringUtils.randomNumeric(10)
				+ fileName.substring(fileName.lastIndexOf("."));
	}


}
